#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_parallel_parm_refresh.sh
##  Functions : 
##  Purpose   : 
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
###############################################################################

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

function USAGE(){
    echo -e "\nHow to use this shell script!"
    echo -e '\n${V_SHELL_HOME}/edw_parallel_parm_refresh.sh 20170101'
}

# Check variable
if [[ -z ${1} ]];then
    USAGE
    exit 1
fi

# Define basic parm
V_SCRIPT_NAME=$(basename ${0} | cut -d'.' -f1)
V_OUT_LOGS="${V_SHELL_LOGS}/${V_SCRIPT_NAME}_${V_TIME_STAMP}_$$.log"

# Define the output flow
exec 4>&1               # screen output
exec 3>>${V_OUT_LOGS}   # script output
exec 2>&3               # error output
exec 1>&3               # standard output
echo -e "[Begin: $(date +%F) $(date +%T)]"

# Define the parm
V_DATA_DATE=${1}

# Get org info
V_QUERY="SELECT ORG_NO FROM ETL.EDW_ORG_INFO WHERE IF_VALID <> 'N';"
V_ORG_LIST=($(${V_RUN_MYSQL} -q "${V_QUERY}"))
if [[ $? -ne 0 ]];then
    echo -e "\nERROR:Can not get the org list"
    echo -e "\n${V_QUERY}"
    exit 1
else
    echo -e "\nSuccess to get the org list."
fi

# Parallel refresh parm
echo -e "\n[------------------------Parallel Refresh Parm------------------------]"
for ((i=0; i<${#V_ORG_LIST[@]}; i++));do
    if [[ ${V_DATA_DATE:4:4} == '1331' ]]
    then
      sh ${V_REFRESH_P_1331} ${V_DATA_DATE} ${V_ORG_LIST[i]} &
      V_PARM_PID[i]=$(echo ${!})
      echo -e "Start to call[${V_PARM_PID[i]}]:${V_REFRESH_P} ${V_DATA_DATE} ${ORG}" 
    else
      sh ${V_REFRESH_P} ${V_DATA_DATE} ${V_ORG_LIST[i]} &
      V_PARM_PID[i]=$(echo ${!})
      echo -e "Start to call[${V_PARM_PID[i]}]:${V_REFRESH_P} ${V_DATA_DATE} ${ORG}"
    fi
done

# Check the parm PID
echo -e "\nStarting to check parm..."
for ((i=0; i<${#V_PARM_PID[@]}; i++));do
    # Get the return code
    wait ${V_PARM_PID[i]}
    if [[ $? -eq 0 ]];then
        echo -e "${V_PARM_PID[i]} has done."
    else
        x=fail
        echo -e "ERROR[${V_PARM_PID[i]}]:Fail to refresh the parm file."
    fi
done

# Check all
if [[ ${x} == "fail" ]];then
    exit 1
fi

echo -e "\n[End: $(date +%F) $(date +%T)]"
echo 0 >&4
exit 0
